/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.restaurant.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springblade.common.tool.CommonUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.restaurant.entity.ExpensesBudget;
import org.springblade.modules.restaurant.excel.ExpensesBudgetExcel;
import org.springblade.modules.restaurant.service.IExpensesBudgetService;
import org.springblade.modules.restaurant.vo.ExpensesBudgetVO;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 预算支出表 控制器
 *
 * @author Blade
 * @since 2025-03-03
 */
@RestController
@AllArgsConstructor
@RequestMapping("/restaurant/expensesbudget")
@Tag(name = "预算支出表", description = "预算支出表接口")
public class ExpensesBudgetController extends BladeController {

	private IExpensesBudgetService expensesBudgetService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入expensesBudget")
	public R<ExpensesBudget> detail(ExpensesBudget expensesBudget) {
		ExpensesBudget detail = expensesBudgetService.getOne(Condition.getQueryWrapper(expensesBudget));
		return R.data(detail);
	}

	/**
	 * 分页 预算支出表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入expensesBudget")
	public R<IPage<ExpensesBudget>> list(ExpensesBudgetVO expensesBudget, Query query) {
		IPage<ExpensesBudget> pages = expensesBudgetService.page(Condition.getPage(query), customizeQueryWrapper(expensesBudget));
		return R.data(pages);
	}


	/**
	 * 自定义分页 预算支出表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "分页", description = "传入expensesBudget")
	public R<IPage<ExpensesBudgetVO>> page(ExpensesBudgetVO expensesBudget, Query query) {
		IPage<ExpensesBudgetVO> pages = expensesBudgetService.selectExpensesBudgetPage(Condition.getPage(query), expensesBudget);
		return R.data(pages);
	}

	/**
	 * 新增 预算支出表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增", description = "传入expensesBudget")
	public R save(@Valid @RequestBody ExpensesBudget expensesBudget) {

		String businessTime = expensesBudget.getBusinessTime();
		int days = CommonUtil.getDays(businessTime, DatePattern.NORM_MONTH_PATTERN);
		expensesBudget.setDays(days);
		BigDecimal dailyExpendAmount = expensesBudget.getMonthlyExpendAmount().divide(new BigDecimal(days), 2, RoundingMode.HALF_UP);
		expensesBudget.setDailyExpendAmount(dailyExpendAmount);

		return R.status(expensesBudgetService.save(expensesBudget));
	}

	/**
	 * 修改 预算支出表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description = "传入expensesBudget")
	public R update(@Valid @RequestBody ExpensesBudget expensesBudget) {
		String businessTime = expensesBudget.getBusinessTime();
		int days = CommonUtil.getDays(businessTime, DatePattern.NORM_MONTH_PATTERN);
		expensesBudget.setDays(days);
		BigDecimal dailyExpendAmount = expensesBudget.getMonthlyExpendAmount().divide(new BigDecimal(days), 2, RoundingMode.HALF_UP);
		expensesBudget.setDailyExpendAmount(dailyExpendAmount);

		return R.status(expensesBudgetService.updateById(expensesBudget));
	}

	/**
	 * 新增或修改 预算支出表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description = "传入expensesBudget")
	public R submit(@Valid @RequestBody ExpensesBudget expensesBudget) {

		String businessTime = expensesBudget.getBusinessTime();
		int days = CommonUtil.getDays(businessTime, DatePattern.NORM_MONTH_PATTERN);
		expensesBudget.setDays(days);
		BigDecimal dailyExpendAmount = expensesBudget.getMonthlyExpendAmount().divide(new BigDecimal(days), 2, RoundingMode.HALF_UP);
		expensesBudget.setDailyExpendAmount(dailyExpendAmount);

		return R.status(expensesBudgetService.saveOrUpdate(expensesBudget));
	}

	/**
	 * 删除 预算支出表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.status(expensesBudgetService.deleteLogic(Func.toLongList(ids)));
	}


	@SneakyThrows
	@GetMapping("/export")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出", description = "传入ids")
	public void export(ExpensesBudgetVO budget, HttpServletResponse response) {
		List<ExpensesBudget> list = expensesBudgetService.list(customizeQueryWrapper(budget));
		List<ExpensesBudgetExcel> excels = BeanUtil.copyToList(list, ExpensesBudgetExcel.class);

		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		String fileName = URLEncoder.encode("预算支出", StandardCharsets.UTF_8)
			+ "_" + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN);

		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), ExpensesBudgetExcel.class).sheet("预算支出").doWrite(excels);
	}

	private Wrapper<ExpensesBudget> customizeQueryWrapper(ExpensesBudgetVO expensesBudget) {
		String businessTime = expensesBudget.getBusinessTime();
		if (ObjectUtil.isEmpty(businessTime)) {
			businessTime = DateUtil.format(DateUtil.date(), DatePattern.NORM_MONTH_PATTERN);
		}
		return Wrappers.<ExpensesBudget>lambdaQuery()
			.eq(ExpensesBudget::getBusinessTime, businessTime)
			.eq(ObjectUtil.isNotEmpty(expensesBudget.getStatus()), ExpensesBudget::getStatus, expensesBudget.getStatus())
			.orderByDesc(ExpensesBudget::getBusinessTime);
	}
}
